package com.kt.controller;

import com.kt.domain.Category;
import com.kt.domain.Product;
import com.kt.service.imp.CategoryServiceImp;
import com.kt.service.imp.ProductServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addProduct.do")
public class ChangeProductInfoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ProductServiceImp productServiceImp = new ProductServiceImp();
        Product product = productServiceImp.findById(req.getParameter("pid"));
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");

        if (product == null) {
            resp.getWriter().write("商品不存在");
            return;
        }
        String cname = req.getParameter("cname");
        CategoryServiceImp categoryServiceImp = new CategoryServiceImp();
        Category category = categoryServiceImp.findByName(cname);
        if (category == null) {
            category = new Category();
            category.setCname(cname);
            categoryServiceImp.addCategory(category);
        }

        String pname = req.getParameter("pname");
        product.setPname(pname);
        product.setPrice(Double.valueOf(req.getParameter("price")));
        product.setBrand(req.getParameter("brand"));
        product.setDesc(req.getParameter("pdesc"));
        product.setPicture(req.getParameter("picture"));
        product.setCid(category.getCid());
        int result = productServiceImp.addProduct(product);
        if (result == 0) {
            resp.getWriter().write("商品名已存在");
            return;
        }
        resp.getWriter().write("商品信息修改成功");
    }
}
